﻿using Files.Common;
using Files.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Script.Serialization;
using System.Data;
using System.Data.SqlClient;
using API.Models;
using System.Text;
using Dapper;

namespace API.Controllers
{

    //[EnableCors(origins: "*", headers: "*", methods: "*")]
    //[CustomActionFilterAttribute]
    public class AccountController : ApiController
    {
        public string Options()
        {
            return null;
        }

        #region [注册相关]

        [HttpPost, HttpGet]
        public string register(int CompetitionTypeId, int EventsId, int ParticipantsTypeId, string Organization, string Members, string Account, string Password, string Phone, string Remark, int IsEnable)
        {
            Message ms = new Message();

            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("select * from ZX_Group where Account='{0}'", Account);
                List<ZX_Group> list = db.Query<ZX_Group>(sb.ToString(), null).ToList();
                if (list.Count > 0)
                {
                    ms.success = false;
                    ms.code = "0000";
                    ms.msg = "账户已注册，请重新填写账号";
                    ms.data = null;
                }
                else
                {
                    StringBuilder sb1 = new StringBuilder();
                    IsEnable = 1;

                    sb1.AppendFormat("insert into ZX_Group values({0},{1},{2},'{3}','{4}','{5}','{6}','{7}','{8}',{9},'{10}','{11}')", CompetitionTypeId, EventsId, ParticipantsTypeId, Organization, Members, Account, Password, Phone, Remark, IsEnable, DateTime.Now, DateTime.Now);
                    int count = db.Execute(sb1.ToString());
                    if (count > 0)
                    {

                        ms.success = true;
                        ms.code = "1111";
                        ms.msg = "注册成功，即将跳转";
                        ms.data = "";
                    }
                    else
                    {
                        ms.success = false;
                        ms.code = "0000";
                        ms.msg = "注册失败，请重新尝试";
                        ms.data = null;
                    }
                }
            }

            var result = new { data = ms };
            return new JavaScriptSerializer().Serialize(result);
        }


        /// <summary>
        /// 赛项--下拉框绑定
        /// </summary>
        /// <returns></returns>
        [HttpPost, HttpGet]
        public IHttpActionResult EventsList()
        {
            Message ms = new Message();
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from ZX_Events");
                List<ZX_Events> list = db.Query<ZX_Events>(sb.ToString(), null).ToList();

                ms.success = true;
                ms.code = "1111";
                ms.msg = "请求成功";
                ms.data = new JavaScriptSerializer().Serialize(list);

                return Json(new { data = ms });
            }
        }

        /// <summary>
        /// 根据大赛类型查询赛项
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>

        [HttpGet, HttpPost]
        public IHttpActionResult queryEventsListByCompetitionTypeId(int Id)
        {
            Message ms = new Message();
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("select * from ZX_Events where CompetitionTypeId={0}", Id);
                List<ZX_Events> list = db.Query<ZX_Events>(sb.ToString(), null).ToList();

                ms.success = true;
                ms.code = "1111";
                ms.msg = "请求成功";
                ms.data = new JavaScriptSerializer().Serialize(list);

                return Json(new { data = ms });
            }
        }

        /// <summary>
        /// 大赛类型--绑定下拉框
        /// </summary>
        /// <returns></returns>

        [HttpGet, HttpPost]
        public IHttpActionResult CompetitionTypeList()
        {
            Message ms = new Message();
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from ZX_CompetitionType");
                List<ZX_CompetitionType> list = db.Query<ZX_CompetitionType>(sb.ToString(), null).ToList();

                ms.success = true;
                ms.code = "1111";
                ms.msg = "请求成功";
                ms.data = new JavaScriptSerializer().Serialize(list);

                return Json(new { data = ms });
            }
        }

        /// <summary>
        /// 参赛人员类型--下拉框绑定
        /// </summary>
        /// <returns></returns>

        [HttpPost, HttpGet]
        public IHttpActionResult ParticipantsTypeList()
        {
            Message ms = new Message();
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from ZX_ParticipantsType");
                List<ZX_ParticipantsType> list = db.Query<ZX_ParticipantsType>(sb.ToString(), null).ToList();

                ms.success = true;
                ms.code = "1111";
                ms.msg = "请求成功";
                ms.data = new JavaScriptSerializer().Serialize(list);

                return Json(new { data = ms });
            }
        }

        #endregion

        #region[登录相关]
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>

        [HttpPost, HttpGet]
        public IHttpActionResult Login(string account, string password)
        {

            Message ms = new Message();
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("select * from ZX_Group where Account='{0}' and Password='{1}'", account, password);
                List<ZX_Group> list = db.Query<ZX_Group>(sb.ToString(), null).ToList();

                if (list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        if (item.IsEnable != 1)
                        {
                            ms.success = true;
                            ms.code = "0001";
                            ms.msg = "当前账户不可用";
                            ms.data = null;
                        }
                        else
                        {
                            System.Web.HttpContext.Current.Session["eventId"] =Convert.ToString(item.EventsId);
                            System.Web.HttpContext.Current.Session["userId"] = Convert.ToString(item.Id);
                            System.Web.HttpContext.Current.Session["account"] = Convert.ToString(item.Account);
                            System.Web.HttpContext.Current.Session["IdentityInformation"] = Convert.ToString(item.IdentityInformation);

                            System.Web.HttpContext.Current.Session.Timeout = 5000;
                            ms.success = true;
                            ms.code = "1111";
                            ms.msg = "登录成功，即将跳转...";
                            ms.data = new JavaScriptSerializer().Serialize(list);
                        }
                    }
                }
                else
                {
                    ms.success = false;
                    ms.code = "0000";
                    ms.msg = "登录失败，请重试";
                    ms.data = new JavaScriptSerializer().Serialize(list);
                }
            }
            return Json(new
            {
                data = ms
            });
        }

        #endregion

        #region[个人中心]

        [HttpPost, HttpGet]
        public IHttpActionResult queryById(int Id)
        {
            Message ms = new Message();
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendFormat(@"select g.Id,g.CompetitionTypeId,g.EventsId,g.ParticipantsTypeId,g.Organization,g.Members,
                                 g.Account, g.Password, g.Phone, g.Remark, g.IsEnable, g.InsertTime, g.UpdateTime,
                                 c.Name as CName, p.Name as PName, e.Name as EName
                                 from ZX_Group g left join ZX_CompetitionType c on g.CompetitionTypeId = c.Id
                                 left join ZX_Events e
                                 on g.EventsId = e.id left
                                 join ZX_ParticipantsType p on g.ParticipantsTypeId = p.Id where g.Id = {0}", Id);

                List<ZX_Group> list = db.Query<ZX_Group>(sb.ToString(), null).ToList();
                if (list.Count > 0)
                {
                    ms.success = true;
                    ms.code = "1111";
                    ms.msg = "查询成功";
                    ms.data = new JavaScriptSerializer().Serialize(list);
                }
                else
                {
                    ms.success = false;
                    ms.code = "0000";
                    ms.msg = "查询失败";
                    ms.data = new JavaScriptSerializer().Serialize(list);
                }
            }
            return Json(new { data = ms });
        }

        /// <summary>
        /// 修改个人信息
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="CompetitionTypeId"></param>
        /// <param name="EventsId"></param>
        /// <param name="ParticipantsTypeId"></param>
        /// <param name="Organization"></param>
        /// <param name="Members"></param>
        /// <param name="Account"></param>
        /// <param name="Password"></param>
        /// <param name="Phone"></param>
        /// <param name="Remark"></param>
        /// <param name="IsEnable"></param>
        /// <returns></returns>

        [HttpPost, HttpGet]
        public string Edit(int Id, int CompetitionTypeId, int EventsId, int ParticipantsTypeId, string Organization, string Members, string Account, string Password, string Phone, string Remark, int IsEnable)
        {
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                Message ms = new Message();
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat(@"update ZX_Group set CompetitionTypeId={0},EventsId={1},ParticipantsTypeId={2},Organization='{3}',
Members = '{4}', Account = '{5}', Password = '{6}', Phone = '{7}', Remark = '{8}', IsEnable ={ 9},UpdateTime = '{10}' where Id={11}", CompetitionTypeId, EventsId, ParticipantsTypeId, Organization, Members, Account, Password, Phone, Remark, IsEnable, Id);

                int count = db.Execute(sb.ToString());
                if (count > 0)
                {
                    ms.success = true;
                    ms.code = "1111";
                    ms.msg = "修改成功";
                    ms.data = "";
                }
                else
                {
                    ms.success = false;
                    ms.code = "0000";
                    ms.msg = "修改失败";
                    ms.data = null;
                }
                return new JavaScriptSerializer().Serialize(ms);
            }

        }

        #endregion
    }
}
